// SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later

#include "eventreceiver.h"
#include "common/common.h"
#include "services/project/projectservice.h"
#include "services/window/windowservice.h"
#include "manage/clockmanage.h"
#include <QSet>
#include <QMap>
#include <QString>
#include <QProcess>
#include <QDir>
extern const char *D_TSET;
using dpfservice::ProjectService;
using dpfservice::WindowService;
EventReceiverDemo::EventReceiverDemo(QObject *parent)
    : dpf::EventHandler(parent), dpf::AutoEventHandlerRegister<EventReceiverDemo>()
{
  using namespace std::placeholders;
  eventHandleMap.insert(project.activatedProject.name, std::bind(&EventReceiverDemo::handleOpenProjectEvent, this, _1));
}

dpf::EventHandler::Type EventReceiverDemo::type()
{
  return dpf::EventHandler::Type::Async;
}

QStringList EventReceiverDemo::topics()
{
  return {T_MENU, project.topic};
}

void EventReceiverDemo::eventProcess(const dpf::Event &event)
{
  const auto &eventName = event.data().toString();
  if (!eventHandleMap.contains(eventName))
    return;

  eventHandleMap[eventName](event);
}

void EventReceiverDemo::handleOpenProjectEvent(const dpf::Event &event)
{

  QMetaObject::invokeMethod(this, [event]()
                            {
                                  auto windowService = dpfGetService(dpfservice::WindowService);
                                //   初始化配置文件
                                  QSettings *m_iniFile = new QSettings("src/plugins/myClock/data.ini", QSettings::IniFormat);
                                  // 清除[chart]组下的所有键
                                  m_iniFile->beginGroup("chart");
                                  QStringList keys = m_iniFile->allKeys(); // 获取所有键
                                  foreach (const QString &key, keys) {
                                    m_iniFile->remove(key); // 删除每个键
                                  }
                                  m_iniFile->endGroup(); // 退出[ip]组
                                  auto projectService = dpfGetService(dpfservice::ProjectService);
                                  auto prjInfo = projectService->getActiveProjectInfo();
                                  QString workspaceFolder=prjInfo.workspaceFolder();
                                  auto kitName=prjInfo.kitName();
                                  /**
                                  if(!kitName.isNull()){
                                    // 文件类型数
                                    QMap<QString, int> fileCounts;
                                    // 代码量
                                    QMap<QString, int> lineCounts;
                                    // 总代码量
                                    int totalLines = 0;
                                    QProcess findProcess;
                                    findProcess.setWorkingDirectory(workspaceFolder);
                                    QString command=QString("find . -type f | sed 's/.*\\.//' | sort | uniq -c");
                                    findProcess.start("bash", QStringList() << "-c"<< command);
                                    findProcess.waitForFinished();
                                    QString findOutput = findProcess.readAllStandardOutput();

                                    // 文件类型统计
                                    QStringList fileTypeLines = findOutput.split("\n", Qt::SkipEmptyParts);
                                    foreach (const QString &line, fileTypeLines)
                                    {
                                        QStringList parts = line.simplified().split(" ");
                                        if (parts.size() == 2)
                                        {
                                            int count = parts[0].toInt();
                                            QString extension = parts[1];
                                            fileCounts[extension] = count;
                                        }
                                    }

                                    // 代码量统计
                                    for (auto it = fileCounts.begin(); it != fileCounts.end(); ++it)
                                    {
                                        QString extension = it.key();
                                        QProcess grepProcess;
                                        grepProcess.setWorkingDirectory(workspaceFolder);
                                        QString command = QString("find . -type f -name \"*.%1\" -exec grep -v \"^$\" {} + | wc -l")
                                                            .arg(extension);
                                        grepProcess.start("bash", QStringList() << "-c" << command);
                                        grepProcess.waitForFinished();
                                        QString grepOutput = grepProcess.readAllStandardOutput();
                                        int lineCount = grepOutput.trimmed().toInt();

                                        lineCounts[extension] = lineCount;
                                        totalLines += lineCount;
                                    }

                                    for (auto it = lineCounts.begin(); it != lineCounts.end(); ++it)
                                    {
                                        QString result = QString("%1 : %2").arg(it.key()).arg(it.value());
                                        windowService->notify(1, "Line counts", result, {});
                                    }

                                    for (auto it = fileCounts.begin(); it != fileCounts.end(); ++it)
                                    {
                                        QString result = QString("%1 : %2").arg(it.key()).arg(it.value());
                                        windowService->notify(1, "File counts", result, {});
                                    }
                                    windowService->notify(1, "Total counts", QString::number(totalLines), {});
                                  }
                                  */
                                  auto sourceFiles = prjInfo.sourceFiles();
                                  QMap<QString, int> extensionCounts;

                                  foreach (const QString &source, sourceFiles)
                                  {
                                      QString extension = source.section('.', -1, -1);
                                      extensionCounts[extension]++;
                                  }
                                  for (auto it = extensionCounts.constBegin(); it != extensionCounts.constEnd(); ++it)
                                  {
                                      QString path="chart/"+it.key();
                                      m_iniFile->setValue(path, it.value());
                                  } 
                                Q_EMIT EventReceiverProxy::instance()->chartUpdated(); 
                                Q_EMIT EventReceiverProxy::instance()->tableUpdate(); 
                                });
}

EventReceiverProxy::EventReceiverProxy()
{
}

EventReceiverProxy *EventReceiverProxy::instance()
{
  static EventReceiverProxy proxy;
  return &proxy;
}
